﻿using UnityEngine;
using System.Collections;

namespace DragonRescue3D
{
    /// <summary>
    /// Main gameplay manager class.  This class manages the scoreboard,  finished level status and messages 
    /// and controls and updates the score
    /// </summary>
    public class GamePlayManager : MonoBehaviour
    {
        ScoreBoard _scoreBoard;
        bool _finishedLevel = false;
        bool _updatingStatus = false;
        public EndLvlMsg _msgPrefab;
        public AudioClip _backgroundMusic;
        public GameObject Rocket;

        //--------------------------------------------------------
        /// <summary>
        /// Check sound on/off status, get/set the current score and update the scoreboard
        /// </summary>
        void Start()
        {
            _scoreBoard = GameObject.FindObjectOfType(typeof(ScoreBoard)) as ScoreBoard;

            if (_scoreBoard != null)
            {
                // Get the current score (if we have one)
                if (PlayerPrefs.HasKey("DragonRescue3D.Score"))
                {
                    int currentScore = PlayerPrefs.GetInt("DragonRescue3D.Score");
                    _scoreBoard.SetScore(currentScore);
                }
                else // Otherwise just initialise it to 0
                {
                    _scoreBoard.SetScore(0);
                    PlayerPrefs.SetInt("DragonRescue3D.Score", 0);
                }
            }
            // Now check to make sure the sound is set correctly
            AudioListener.pause = !IsSoundActive;

            GetComponent<AudioSource>().clip = _backgroundMusic;
            GetComponent<AudioSource>().Play();
        }

        //--------------------------------------------------------
        /// <summary>
        /// Start the coroutine to update the status
        /// </summary>
        public void UpdateStatus()
        {
            // If we haven't already completed the level and were not already in the 
            // process of performing an update then start one
            if (gameObject.activeInHierarchy && !_finishedLevel && !_updatingStatus)
            {
                StartCoroutine("UpdateStatusCR");
            }
        }

        //--------------------------------------------------------
        /// <summary>
        /// Checks to see if we have finished the level, and if so 
        /// displays the appropriate success/fail message
        /// </summary>
        IEnumerator UpdateStatusCR()
        {
            _updatingStatus = true;
            // Wait a little bit for other rigidbodies in the scene to update
            // and settle into place.  Also nice to have a bit of a delay before 
            // any messages pop up.
            yield return new WaitForSeconds(4);

            Object[] blocks = GameObject.FindObjectsOfType(typeof(DestructibleBlock));
            Object[] remainingDragons = GameObject.FindObjectsOfType(typeof(Dragon));
            bool matchingBlocksRemaining = false;

            // Go through all the blocks in the scene and check if we have anymore options
            foreach (DestructibleBlock block in blocks)
            {
                if (block.FindAdjacentBlocks().Count > 0)
                {
                    matchingBlocksRemaining = true;
                    break;
                }
            }

            // If we have rescued all the dragons then we win!
            if ( remainingDragons.Length == 0)
            {
                _finishedLevel = true;
                // Create an end of level message object
                Vector3 msgPos = new Vector3(transform.position.x, transform.position.y, -6.5f);
                EndLvlMsg endLvlOptions = Instantiate(_msgPrefab, msgPos, transform.rotation) as EndLvlMsg;
                GetComponent<AudioSource>().Stop();
                endLvlOptions.ShowLevelSucceeded();
            } // Otherwise if there is no chance to save the remaining ones then we have failed!
            else if ( !matchingBlocksRemaining && blocks.Length > 0 && Rocket == null )
            {
                _finishedLevel = true;
                // Create an end of level message object
                Vector3 msgPos = new Vector3(transform.position.x, transform.position.y, -6.5f);
                EndLvlMsg endLvlOptions = Instantiate(_msgPrefab, msgPos, transform.rotation) as EndLvlMsg;
                GetComponent<AudioSource>().Stop();
                endLvlOptions.ShowLevelFailed(remainingDragons.Length);
            }
            _updatingStatus = false;
        }

        //--------------------------------------------------------
        /// <summary>
        /// Add an amount to the existing socre and update the socoreboard
        /// </summary>
        /// <param name="score"></param>
        public void AddScore(int score)
        {
            int currentScore = PlayerPrefs.GetInt("DragonRescue3D.Score") + score;
            PlayerPrefs.SetInt("DragonRescue3D.Score", currentScore);
            _scoreBoard.SetScore(currentScore);
        }

        //--------------------------------------------------------
        /// <summary>
        /// Pauses/plays the scene's audiolistener and updates the player preference
        /// </summary>
        /// <param name="playSounds"></param>
        public void ActivateSounds(bool playSounds)
        {
            if (playSounds)
            {
                PlayerPrefs.SetInt("DragonRescue3D.Sound", 1);
                AudioListener.pause = false;
            }
            else
            {
                PlayerPrefs.SetInt("DragonRescue3D.Sound", 0);
                AudioListener.pause = true;
            }
        }

        //--------------------------------------------------------
        /// <summary>
        /// Checks to see if the user has turned on/off the game sound from the main menu
        /// </summary>
        public bool IsSoundActive
        {
            get
            {
                bool retVal = false;
                int soundFlag = PlayerPrefs.GetInt("DragonRescue3D.Sound");

                // If the preference was set to 1 then the sound is turned on
                if (soundFlag == 1)
                {
                    retVal = true;
                }
                else // otherwise it's off
                {
                    retVal = false;
                }
                return retVal;
            }
        }
    }
}

#if NO_AND_ERROR
public void TEXT1() 
{
	int textNum = 1;
	if (textNum == 1) 
	{
		textNum = 2;
    }
}
public void TEXT2()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}
public void TEXT3()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT4()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT5()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT6()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT8()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT9()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT10()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT11()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT12()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT13()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT14()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT15()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT16()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}

public void TEXT17()
{
    int textNum = 1;
    if (textNum == 1)
    {
        textNum = 2;
    }
}
#endif